package cn.spark.streaming;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;

/**
 * Database Initilization
 * @author Administrator
 *
 */
public class ConnectionPool {

    // Setup a static Connection Queue
    private static LinkedList<Connection> connectionQueue;

    /**
     * Load MySQL driver
     */
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Return a database connection from connection pool
     * @return
     */
    public synchronized static Connection getConnection() {
        try {
            if(connectionQueue == null) {
                connectionQueue = new LinkedList<Connection>();
                for(int i = 0; i < 10; i++) {
                	//Create 10 connection for the connection pool
                    Connection conn = DriverManager.getConnection(
                            "jdbc:mysql://student28-x1:3306/testdb",
                            "root",
                            "abcd1234");
                    connectionQueue.push(conn);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connectionQueue.poll();
    }

    /**
     * Return the connection object to the connection pool
     */
    public static void returnConnection(Connection conn) {
        connectionQueue.push(conn);
    }

}
